//
//  ChecklistItem.swift
//  Checklists
//
//  Created by M.I. Hollemans on 16/09/14.
//  Copyright (c) 2014 Razeware. All rights reserved.
//

import Foundation
import UIKit

class ChecklistItem: NSObject, NSCoding {
  var text = ""
  var checked = false
	var dueDate = NSDate()
	var shouldRemind = false
	var itemID: Int

	convenience init(text: String) {
		self.init(text: text, checked: false)
	}
	
	init(text: String, checked: Bool) {
		self.text = text
		self.checked = checked
		self.itemID = DataModel.nextChecklistItemID()
		super.init()
	}
	
	required init?(coder aDecoder: NSCoder) {
		text = aDecoder.decodeObjectForKey("Text") as! String
		checked = aDecoder.decodeBoolForKey("Checked")
		dueDate = aDecoder.decodeObjectForKey("DueDate") as! NSDate
		shouldRemind = aDecoder.decodeBoolForKey("ShouldRemind")
		itemID = aDecoder.decodeIntegerForKey("ItemID")
		super.init()
	}
	
	deinit {
		let existingNotification = notificationForThisItem()
		if let notification = existingNotification {
			print("Removing existing notification \(notification)")
			UIApplication.sharedApplication().cancelLocalNotification(notification)
		}
	}
	
	func encodeWithCoder(aCoder: NSCoder) {
		aCoder.encodeObject(text, forKey: "Text")
		aCoder.encodeBool(checked, forKey: "Checked")
		aCoder.encodeObject(dueDate, forKey: "DueDate")
		aCoder.encodeBool(shouldRemind, forKey: "ShouldRemind")
		aCoder.encodeInteger(itemID, forKey: "ItemID")
	}
	
  func toggleChecked() {
    checked = !checked
  }
	
	func dueDateValid() -> Bool {
		if shouldRemind && dueDate.compare(NSDate()) != NSComparisonResult.OrderedAscending {
			return true
		}
		return false
	}
	
	func scheduleNotification() {
		let existingNotification = notificationForThisItem()
		if let notification = existingNotification {
			print("Found an existing notification \(notification)")
			UIApplication.sharedApplication().cancelLocalNotification(notification)
		}
		
		if dueDateValid() {
			let localNotification = UILocalNotification()
			localNotification.fireDate = dueDate
			localNotification.timeZone = NSTimeZone.defaultTimeZone()
			localNotification.alertBody = text
			localNotification.soundName = UILocalNotificationDefaultSoundName
			localNotification.userInfo = ["ItemID": itemID]
			
			UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
			print("Scheduled notification \(localNotification) for itemID \(itemID)")
		}
	}
	
	func notificationForThisItem() -> UILocalNotification? {
		let allNotifications = UIApplication.sharedApplication().scheduledLocalNotifications! as [UILocalNotification]
		for notification in allNotifications {
			if let number = notification.userInfo?["ItemID"] as? NSNumber {
				if number.integerValue == itemID {
					return notification
				}
			}
		}
		return nil
	}
}
